import App from './App.vue';
import { routerMaker } from '@/router';
import type { UserModule } from './types';
import type { App as VueApp } from 'vue';
import './styles';
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import '../src/styles/style.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
const bootstrap = (app?: VueApp) => {
  // eslint-disable-next-line no-param-reassign
  app = createApp(App);

  const router = routerMaker();
  const currentApp = app as VueApp;
  app.use(router);
  app.use(ElementPlus)
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
  }
  
  const microEnv = window?.$wujie?.props;
  Object.values(
    import.meta.glob<{ install: UserModule }>('./modules/*.ts', {
      eager: true,
    }),
  ).forEach((i) => i.install?.({ app: currentApp, router, microEnv }));
  app.mount('#app');
  return currentApp;
};

// Singleton instance applied to the sub application
if (window.__POWERED_BY_WUJIE__) {
  // initial data from base app by [window.$wujie.props]
  // const { token, locale, theme } = window.$wujie.props;
  const  {token, locale, theme, userInfo}  = window.$wujie.props;
  sessionStorage.setItem('userInfo',(JSON.stringify(userInfo)))
  let instance: any;
  window.__WUJIE_MOUNT = () => {
    instance = bootstrap(instance);
  };
  window.__WUJIE_UNMOUNT = () => {
    instance.unmount();
  };
  /*
    由于vite是异步加载，而无界可能采用fiber执行机制
    所以mount的调用时机无法确认，框架调用时可能vite
    还没有加载回来，这里采用主动调用防止用没有mount
    无界mount函数内置标记，不用担心重复mount
  */
  window.__WUJIE?.mount();
} else {
  bootstrap();
}
